<template>
  <div class="events">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">演出列表</h1>
        <p class="page-subtitle">发现更多精彩演出</p>
      </div>

      <!-- 搜索和筛选 -->
      <div class="filters">
        <div class="filters__search">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索演出名称、场馆..."
            class="search-input"
            @input="handleSearch"
          />
          <button class="search-btn" @click="handleSearch">
            🔍
          </button>
        </div>
        
        <div class="filters__options">
          <select v-model="selectedCategory" @change="handleFilter" class="filter-select">
            <option value="">全部分类</option>
            <option v-for="category in categories" :key="category" :value="category">
              {{ category }}
            </option>
          </select>
          
          <input
            v-model="addressKeyword"
            type="text"
            placeholder="地址关键词（城市/地址片段）"
            class="filter-input"
            @input="handleFilter"
          />

          <select v-model="sortBy" @change="handleSort" class="filter-select">
            <option value="startTime">按时间</option>
            <option value="title">按标题</option>
            <option value="createdAt">按创建时间</option>
            <option value="status">按状态</option>
            <option value="lowestPrice">按最低价</option>
            <option value="popularity">按热度</option>
          </select>

          <select v-model="sortOrder" @change="handleSort" class="filter-select">
            <option value="ASC">升序</option>
            <option value="DESC">降序</option>
          </select>

          <select v-model.number="pageSize" @change="handlePageSizeChange" class="filter-select">
            <option :value="6">每页 6 条</option>
            <option :value="12">每页 12 条</option>
            <option :value="24">每页 24 条</option>
          </select>
        </div>
      </div>

      <!-- 演出列表 -->
      <div class="events-content">
        <div v-if="loading" class="loading">
          <div class="skeleton-grid">
            <div class="skeleton-card" v-for="n in pageSize" :key="n">
              <div class="skeleton-img"></div>
              <div class="skeleton-line short"></div>
              <div class="skeleton-line"></div>
              <div class="skeleton-line"></div>
            </div>
          </div>
        </div>
        
        <div v-else-if="events.length === 0" class="empty">
          <p>暂无符合条件的演出</p>
          <button @click="clearFilters" class="btn btn--secondary">
            清除筛选条件
          </button>
        </div>
        
        <div v-else class="events-grid">
          <div 
            v-for="event in events" 
            :key="event.id"
            class="event-card"
            @click="goToEvent(event.id)"
          >
            <div class="event-card__image">
              <img v-lazy="{ src: event.image, fallback: `${BASE_URL}/images/phantom-opera.svg` }" :alt="event.title" />
              <div class="event-card__badge">{{ event.category }}</div>
              <div v-if="event.isHot" class="event-card__hot">🔥 热门</div>
            </div>
            <div class="event-card__content">
              <h3 class="event-card__title">{{ event.title }}</h3>
              <p class="event-card__venue">📍 {{ event.venue }}</p>
              <p class="event-card__date">📅 {{ formatDate(event.date) }}</p>
              <div class="event-card__footer">
                <div class="event-card__price">
                  <span class="price">¥{{ event.price }}</span>
                  <span class="price-label">起</span>
                </div>
                <button 
                  @click.stop="buyNow(event)"
                  class="btn btn--primary btn--small"
                  :disabled="event.soldOut"
                >
                  {{ event.soldOut ? '已售罄' : '立即购买' }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="totalPages > 1 || totalElements > 0">
          <div class="pagination__info">共 {{ totalElements }} 条</div>
          <button 
            @click="goToPage(currentPage - 1)"
            :disabled="currentPage === 1"
            class="pagination__btn"
          >
            上一页
          </button>
          
          <div class="pagination__numbers">
            <template v-for="page in visiblePages" :key="`p-${page}`">
              <button
                v-if="typeof page === 'number'"
                @click="goToPage(page)"
                :class="['pagination__number', { active: page === currentPage }]"
              >
                {{ page }}
              </button>
              <span v-else class="pagination__ellipsis">{{ page }}</span>
            </template>
          </div>
          
          <button 
            @click="goToPage(currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="pagination__btn"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { apiClient, BASE_URL } from '@/api/client'

const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const selectedCategory = ref('')
const addressKeyword = ref('')
const sortBy = ref('startTime')
const sortOrder = ref('ASC')
const currentPage = ref(1)
const pageSize = ref(12)
const totalPages = ref(0)
const totalElements = ref(0)

// 演出数据（从后端加载）
const events = ref([])

// 分类和城市选项
const categories = computed(() => {
  return [...new Set(events.value.map(event => event.category))]
})

// 取消城市筛选，改为地址关键词输入

// 筛选后的演出
const filteredEvents = computed(() => {
  let result = events.value

  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(event => 
      event.title.toLowerCase().includes(query) ||
      event.venue.toLowerCase().includes(query)
    )
  }

  // 分类筛选
  if (selectedCategory.value) {
    result = result.filter(event => event.category === selectedCategory.value)
  }

  // 地址关键词在服务端处理，这里不再做本地城市筛选

  // 排序
  result.sort((a, b) => {
    switch (sortBy.value) {
      case 'price':
        return a.price - b.price
      case 'popularity':
        return b.isHot - a.isHot
      case 'date':
      default:
        return new Date(a.date) - new Date(b.date)
    }
  })

  return result
})

// 分页相关计算属性
// 使用服务端分页，totalPages 由响应设置

// 使用服务端分页，直接使用 events

const visiblePages = computed(() => {
  const pages = []
  const total = totalPages.value
  const current = currentPage.value
  
  if (total <= 7) {
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    if (current <= 4) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...', total)
    } else if (current >= total - 3) {
      pages.push(1, '...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1, '...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...', total)
    }
  }
  
  return pages
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
  loadEvents(0)
}

const handleFilter = () => {
  currentPage.value = 1
  loadEvents(0)
}

const handleSort = () => {
  currentPage.value = 1
  loadEvents(0)
}

const handlePageSizeChange = () => {
  currentPage.value = 1
  loadEvents(0, pageSize.value)
}

const clearFilters = () => {
  searchQuery.value = ''
  selectedCategory.value = ''
  addressKeyword.value = ''
  sortBy.value = 'startTime'
  sortOrder.value = 'ASC'
  currentPage.value = 1
  loadEvents(0, pageSize.value)
}

const goToPage = (page) => {
  if (typeof page !== 'number') return
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadEvents(page - 1)
  }
}

const goToEvent = (eventId) => {
  router.push(`/event/${eventId}`)
}

const buyNow = (event) => {
  if (event.soldOut) return
  router.push({ path: `/event/${event.id}`, query: { buyNow: '1' } })
}

const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 监听路由参数变化
watch(() => route.query, (newQuery) => {
  if (newQuery.category) {
    selectedCategory.value = newQuery.category
  }
}, { immediate: true })

// 组件挂载时的初始化
onMounted(() => {
  loadEvents(0, pageSize.value)
})

async function loadEvents(page = 0, size = pageSize.value) {
  try {
    loading.value = true
    const sortField = sortBy.value || 'startTime'
    const params = new URLSearchParams({
      page: String(page),
      size: String(size),
      sortBy: sortField,
      order: sortOrder.value || 'ASC'
    })
    // 后端仅支持一个 keyword 参数，优先使用地址关键词，否则使用通用搜索词
    if (addressKeyword.value) {
      params.set('keyword', addressKeyword.value)
    } else if (searchQuery.value) {
      params.set('keyword', searchQuery.value)
    }
    if (selectedCategory.value) params.set('category', selectedCategory.value)

    const response = await apiClient.get(`/api/events?${params.toString()}`)
    const data = response?.data || {}
    const content = data?.content || []
    events.value = content.map(e => ({
      id: e.id,
      title: e.title,
      venue: e.venue,
      city: '',
      date: e.startTime,
      price: e.lowestPrice ?? 0,
      category: e.category,
      image: e.posterUrl ? `${BASE_URL}${e.posterUrl}` : `${BASE_URL}/images/phantom-opera.svg`,
      isHot: false,
      soldOut: false
    }))
    totalPages.value = data?.totalPages || 0
    totalElements.value = data?.totalElements || 0
  } catch (err) {
    console.error('加载演出失败', err)
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables' as *;

.events {
  min-height: 100vh;
  padding: $spacing-xl 0;
}

.page-header {
  text-align: center;
  margin-bottom: $spacing-xxl;
  
  .page-title {
    font-size: $font-size-xxl;
    font-weight: $font-weight-bold;
    color: $text-primary;
    margin-bottom: $spacing-sm;
  }
  
  .page-subtitle {
    color: $text-secondary;
    font-size: $font-size-lg;
  }
}

.filters {
  background: white;
  padding: $spacing-lg;
  border-radius: $border-radius-lg;
  box-shadow: $shadow-light;
  margin-bottom: $spacing-xl;
  
  &__search {
    display: flex;
    margin-bottom: $spacing-lg;
    
    .search-input {
      flex: 1;
      padding: $spacing-md;
      border: 1px solid $border-color;
      border-radius: $border-radius-md 0 0 $border-radius-md;
      font-size: $font-size-md;
      
      &:focus {
        outline: none;
        border-color: $primary-color;
      }
    }
    
    .search-btn {
      padding: $spacing-md $spacing-lg;
      background-color: $primary-color;
      color: white;
      border: none;
      border-radius: 0 $border-radius-md $border-radius-md 0;
      cursor: pointer;
      font-size: $font-size-lg;
      
      &:hover {
        background-color: $primary-dark;
      }
    }
  }
  
  &__options {
    display: flex;
    gap: $spacing-md;
    flex-wrap: wrap;
    
    .filter-select {
      padding: $spacing-sm $spacing-md;
      border: 1px solid $border-color;
      border-radius: $border-radius-md;
      font-size: $font-size-md;
      background: white;
      
      &:focus {
        outline: none;
        border-color: $primary-color;
      }
    }

    .filter-input {
      padding: $spacing-sm $spacing-md;
      border: 1px solid $border-color;
      border-radius: $border-radius-md;
      font-size: $font-size-md;
      flex: 1 1 240px;
      
      &:focus {
        outline: none;
        border-color: $primary-color;
      }
    }
  }
}

.events-content {
  .loading,
  .empty {
    text-align: center;
    padding: $spacing-xxl;
    color: $text-secondary;
  }
}

.events-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: $spacing-lg;
  margin-bottom: $spacing-xl;
}

.event-card {
  background: white;
  border-radius: $border-radius-lg;
  overflow: hidden;
  box-shadow: $shadow-light;
  transition: all $transition-normal;
  cursor: pointer;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: $shadow-medium;
  }
  
  &__image {
    position: relative;
    height: 200px;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  &__badge {
    position: absolute;
    top: $spacing-sm;
    right: $spacing-sm;
    background-color: $primary-color;
    color: white;
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-sm;
    font-size: $font-size-sm;
    font-weight: $font-weight-medium;
  }
  
  &__hot {
    position: absolute;
    top: $spacing-sm;
    left: $spacing-sm;
    background-color: $error-color;
    color: white;
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-sm;
    font-size: $font-size-xs;
    font-weight: $font-weight-medium;
  }
  
  &__content {
    padding: $spacing-lg;
  }
  
  &__title {
    font-size: $font-size-lg;
    font-weight: $font-weight-bold;
    margin-bottom: $spacing-sm;
    color: $text-primary;
  }
  
  &__venue,
  &__date {
    color: $text-secondary;
    font-size: $font-size-sm;
    margin-bottom: $spacing-xs;
  }
  
  &__footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: $spacing-md;
  }
  
  &__price {
    .price {
      font-size: $font-size-lg;
      font-weight: $font-weight-bold;
      color: $error-color;
    }
    
    .price-label {
      color: $text-secondary;
      font-size: $font-size-sm;
      margin-left: $spacing-xs;
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: $spacing-sm;
  margin-top: $spacing-xl;
  
  &__btn {
    padding: $spacing-sm $spacing-md;
    border: 1px solid $border-color;
    background: white;
    border-radius: $border-radius-md;
    cursor: pointer;
    
    &:hover:not(:disabled) {
      background-color: $bg-secondary;
    }
    
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
  
  &__numbers {
    display: flex;
    gap: $spacing-xs;
  }
  
  &__number {
    width: 40px;
    height: 40px;
    border: 1px solid $border-color;
    background: white;
    border-radius: $border-radius-md;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    
    &:hover {
      background-color: $bg-secondary;
    }
    
    &.active {
      background-color: $primary-color;
      color: white;
      border-color: $primary-color;
    }
  }
}

// 响应式设计
@media (max-width: $breakpoint-md) {
  .filters {
    &__options {
      .filter-select {
        flex: 1;
        min-width: 120px;
      }
    }
  }
  
  .events-grid {
    grid-template-columns: 1fr;
  }
  
  .pagination {
    &__numbers {
      display: none;
    }
  }
}
</style>